package com.atguigu.gmall.rabbit.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class RabbitConfiguration {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory) ;

        // 生产者确认机制
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if(ack) {
                    log.info("消息成功发给了交换机...");
                }else {
                    log.info("消息发给交换机失败了..., 原因：{}" , cause );
                }
            }

        });

        // 回退机制的回调函数
        rabbitTemplate.setMandatory(true);      // 让rabbitmq把失败的消息传递给生产者
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("replyCode: {} , replyText: {} , exchange: {}  , routingKey:{} , msg: {}" , replyCode , replyText , exchange , routingKey , new String(message.getBody()));
            }
        });

        return rabbitTemplate ;
    }

}
